﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using UsedBookTradeSystem.DBContext;
using UsedBookTradeSystem.Models.Dtos.InputDtos;
using UsedBookTradeSystem.Models.Dtos.OutputDtos;
using UsedBookTradeSystem.Models.Entity;
using UsedBookTradeSystem.Models.Enum;

namespace UsedBookTradeSystem.Controllers.FrontControllers
{
    public class ShopperController : Controller
    {
        private readonly SystemDbContext _ctx;

        public ShopperController(SystemDbContext ctx)
        {
            _ctx = ctx;
        }

        [Authorize(Roles = "User")]
        public async Task<IActionResult> Index()
        {
            var  UserInfo= await _ctx.Users.FirstAsync(x => x.UserName == User.Identity.Name);
            var OrderList = await _ctx.Orders.Include(x => x.User).Include(x => x.BookList).Where(x=>x.User==UserInfo).ToListAsync();
            ViewBag.UserInfo = UserInfo;
            ViewBag.OrderList = OrderList;
            return View();
        }

        [Authorize(Roles = "User")]
        public async Task<IActionResult> UpdateShopper(UpdateUserInput userInput)
        {
            if (string.IsNullOrWhiteSpace(userInput.UserName) ||
                string.IsNullOrWhiteSpace(userInput.Tel) ||
                userInput.Tel.Length != 11)
            {
                TempData["OperateResult"] = "输入不合法！";
                return RedirectToAction(nameof(Index));
            }
            if (!UInt64.TryParse(userInput.Tel, out UInt64 n))
            {
                TempData["OperateResult"] = "请输入正确的手机号码！";
                return RedirectToAction(nameof(Index));
            }
            var user = await _ctx.Users.FirstOrDefaultAsync(x => x.Id == userInput.Id);
            if (user == null)
            {
                TempData["OperateResult"] = "用户不存在！";
                return RedirectToAction(nameof(Index));
            }
            if (!string.IsNullOrWhiteSpace(userInput.PassWord) && !string.IsNullOrWhiteSpace(userInput.ConfirmPassword))
            {
                if (userInput.PassWord == userInput.ConfirmPassword)
                {
                    user.PassWord = userInput.PassWord;
                }
                else
                {
                    TempData["OperateResult"] = "两次密码不一致！";
                    return RedirectToAction(nameof(Index));
                }
            }
            user.UserName = userInput.UserName;
            user.Tel = userInput.Tel;
            user.Gender = userInput.Gender;
            user.Address = userInput.Address;
            _ctx.Users.Update(user);
            await _ctx.SaveChangesAsync();
            TempData["OperateResult"] = "修改成功！";
            if (userInput.PassWord == null && userInput.ConfirmPassword == null) 
            {
                return RedirectToAction("Logout", "Home");
            }
            return RedirectToAction("Shop","Home");
        }


        [Authorize(Roles = "User")]
        public async Task<IActionResult> Show(int id)
        {
            var Order = await _ctx.Orders.Include(x => x.User).Include(x => x.BookList).ThenInclude(p => p.BookInfo).FirstAsync(x => x.Id == id);
            var Orderdetail = Order.BookList.GroupBy(x => x.BookInfo, (k, g) => new CartInfoOutput
            {
                BookInfoId = k.Id,
                BookName = k.BookName,
                BookPicture = k.Picture,
                BookInventory = k.Inventory,
                Price = k.Price,
                BookCount = g.Count(),
                TotolPrice = g.Count() * k.Price
            }).ToList();
            ViewBag.Order = Order;
            ViewBag.Orderdetail = Orderdetail;
            return View();
        }
        [Authorize(Roles = "User")]
        public async Task<IActionResult> Delete(int id)
        {
            var Order = await _ctx.Orders.Include(x => x.User).Include(x => x.BookList).ThenInclude(p => p.BookInfo).FirstAsync(x => x.Id == id);
            List<Book> bookList = new();
            foreach (var item in Order.BookList)
            {
                Book book = new()
                {
                    BookInfo = item.BookInfo,
                    IsDeleted = false,
                    Price = item.Price,
                    IsSell = false
                };
                item.BookInfo.Inventory += 1;
                bookList.Add(book);
            }
            await _ctx.Books.AddRangeAsync(bookList);
            Order.OrderStatus = OrderEnum.Cancel;
            _ctx.Orders.Update(Order);
            await _ctx.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }
}
